﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AteneoLibriBusinessLogic.Entities;

namespace AteneoLibri.Account
{
    public partial class ChangePassword : System.Web.UI.Page
    {
        User user = null;
        bool isPasswordValid = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = Utility.HttpSessionManager.GetWebUser();            
        }

        protected void btnChangePassword_Click(object sender, EventArgs e)
        {
            try
            {
                if (user != null)
                {

                    cvUserPassword.IsValid = user.Password.Equals(Utility.Utility.hash(txtOldPassword.Text.Trim()));

                    if (Page.IsValid)
                    {
                        user.Password = Utility.Utility.hash(txtPassword.Text.Trim());
                        user.RecoveryCode = Utility.Utility.generateRecoveryCode(user.Email);

                        using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
                        {
                            if (service.updateUser(user))
                            {
                                string htmlResource = System.Configuration.ConfigurationManager.AppSettings["MAIL_HTML_RESOURCE"];
                                string template = Server.MapPath(htmlResource);

                                //string cssResource = System.Configuration.ConfigurationManager.AppSettings["MAIL_CSS_RESOURCE"];
                                //string CssEmailTextPath = Server.MapPath(cssResource);

                                Utility.Mail.MailSender mailSender = new Utility.Mail.MailSender();
                                //mailSender.SendEmailWithGraphics(user.Email, "Cambio password", "La tua password è stata cambiata.", template, true);
                                mailSender.SendMail(user.Email, "Cambio password", "La tua password è stata cambiata.", true);
                                Response.Redirect("ChangePasswordSuccess.aspx");
                            }
                            else
                            {
                                Response.Redirect("ChangePasswordDeny.aspx");
                            }
                        }
                    }
                    
                }
                else
                {
                    // Redirect per sessione scaduta
                    Response.Redirect("~/Logout.aspx");
                }
                
            }
            catch (Exception)
            {

                throw;
            }
        }

        protected void btnAnnulla_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Account/Dashboard.aspx");
        }
    }
}